package com.ggggeeennn.studentUser.controller.exam;
import com.ggggeeennn.common.core.controller.BaseController;
import com.ggggeeennn.common.core.domain.AjaxResult;
import com.ggggeeennn.common.utils.AliOssUtil;
import com.ggggeeennn.studentUser.domain.DO.AiQuery;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/ai")
public class AiChatController extends BaseController {

    @Autowired
    private  ChatClient dashScopeChatClient;


    /**
     * ChatClient 简单调用
     */
    @PostMapping("/chat")
    public AjaxResult simpleChat(@RequestBody AiQuery aiQuery) {
//        dashScopeChatClient.prompt(query).stream().content();
        return success(dashScopeChatClient.prompt(String.valueOf(aiQuery)).call().content());
    }

    @PostMapping("/chat/stream") // 新接口，支持流式
    public Flux<String> streamChat(@RequestBody AiQuery aiQuery) throws IOException {
        return dashScopeChatClient.prompt(String.valueOf(aiQuery))
                .stream()
                .content()
                .concatMap(response -> {
                    // 将整个响应作为一个流处理
                    return Flux.fromIterable(
                                    response.codePoints()
                                            .mapToObj(c -> String.valueOf(Character.toChars(c)))
                                            .collect(Collectors.toList())
                            )
                            .delayElements(Duration.ofMillis(50))
                            .subscribeOn(Schedulers.boundedElastic());
                });
    }

//    @PostMapping("/chat/stream")
//    @PreAuthorize("@ss.hasPermi('system:notice:list')")
//    public Flux<ServerSentEvent<String>> streamChat(@RequestBody AiQuery aiQuery) {
//        return dashScopeChatClient.prompt(String.valueOf(aiQuery)).stream().content()
//                .map(chunk -> ServerSentEvent.builder(chunk).build())
//                .onErrorResume(e -> Flux.just(
//                        ServerSentEvent.builder("[ERROR] " + e.getMessage()).build()
//                ))
//                .concatWithValues(ServerSentEvent.builder("[DONE]").build());
//    }


//    @GetMapping("/stream/chat")
//    public Flux<String> simpleChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？")String query, HttpServletResponse response) {
//
//        response.setCharacterEncoding("UTF-8");
//        return dashScopeChatClient.prompt(query).stream().content();
//    }

}
